package com.xframe.common.core.service.command;


import com.xframe.common.core.constant.ErrorConstant;
import com.xframe.common.core.dto.ErrorCode;
import com.xframe.domain.ModelRepositoryFactory;
import com.xframe.domain.repository.SysBaseRepository;
import com.xframe.domain.role.IUserCredentials;
import com.xframe.domain.CommandModel;
import com.xframe.common.core.exception.BusinessException;
import com.xframe.domain.sys.SysModel;
import com.xframe.domain.sys.SysModelConfig;
import com.xframe.domain.sys.SysModelViewConfig;
import com.xframe.domain.views.ModelConfigViewBuilderRunTime;
import com.xframe.xdal.core.exception.DalFrameException;
import com.xframe.xdal.core.serialize.JsonConfigContainer;
import com.xframe.xdal.core.util.StringUtil;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;


/**
 * 功能描述:重新创建模型的默认视图
 *
 * @author xufeng
 * @version 1.0
 * 2022-09-26
 */
public class CreateDefModelView extends BaseCommand {
    @Override
    public Object ProcCommand(CommandModel requestArgs, IUserCredentials userCredentials) throws BusinessException {
        try {
            if (StringUtil.isEmpty(requestArgs.getModelCode())) {
                throw new BusinessException(com.xframe.common.core.dto.ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }
            SysModel sysModel = SysModel.getInstance(requestArgs.getModelCode());
            if (sysModel == null) {
                throw new BusinessException(ErrorCode.DB_RECORD_NOFIND,
                        StringUtil.format(ErrorConstant.DB_RECORD_NOFIND_MSG, requestArgs.getModelCode()));
            }
            List<SysModelConfig> modelConfigList = ModelConfigViewBuilderRunTime.builderView(sysModel, userCredentials);
            SysBaseRepository repository = ModelRepositoryFactory.builder(SysModelViewConfig.class);
            //repository.batchSave(SysModelViewConfig.class, modelConfigList);
            Method method = this.getMethodByName(repository.getClass(), "batchSave", Class.class, Collection.class);
            this.execRepository(repository, method, SysModelViewConfig.class, modelConfigList);

            for (SysModelConfig sysModelConfig : modelConfigList) {
                JsonConfigContainer.getConfigContainer().addConfig(sysModelConfig);
            }
            return "OK";
        } catch (BusinessException businessException) {
            throw businessException;
        } catch (DalFrameException exception) {
            throw new BusinessException(exception.getCode(), exception.getMessage());
        } catch (Exception exception) {
            throw new BusinessException(com.xframe.common.core.dto.ErrorCode.INTERNAL_SERVER_ERROR, exception.getMessage());
        }
    }

    @Override
    public String getBeanName() {
        return "CreateDefModelView";
    }
}
